import { ref } from 'vue'
import { adapter, request } from '@/request'
import is from '@/utils/is'
import { message } from 'ant-design-vue'
import { getKeywordStatistics as getKeywordStatisticsApi } from '@/core/api/analysis'
import type { RequestWrapper } from '@/core/interfaces/common'

// 关键词统计数据接口
export interface KeywordStatisticsItem {
  total: number
  top10: number
  top20: number
  top30: number
}

function getKeywordStatistics() {
  const service = adapter<RequestWrapper<KeywordStatisticsItem>>(request)
  const loading = ref(false)
  const response = ref<Partial<KeywordStatisticsItem>>({})

  const fetch = (params: { orderId: string | number; timeRange?: string | number }) => {
    const { url, method } = getKeywordStatisticsApi()
    loading.value = true

    return service({
      config: {
        url,
        method,
        params
      },
      callback: (res) => {
        response.value = res.data.data
      },
      error: (err) => {
        if (is.error(err)) {
          message.error(err.message || '获取关键词统计数据失败')
          response.value = {}
        }
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}

export default getKeywordStatistics
export { getKeywordStatistics }
